package questionsanswers.app;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;

public class QuestionsAnswersActivity extends Activity {
	private int index=1, max = 0;
	private String PATH = Environment.getExternalStorageDirectory().toString()
			+ "/questions/";
	private TextView tAnswer, tQuestion;
	private String answer;
	private DocumentBuilderFactory dbFactory;
	private DocumentBuilder dBuilder;
	private Document doc;
	private int[] questionRating;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		max = new File(PATH).listFiles().length-1;
		questionRating = new int[max];
		setQuestionRating(50);

		tQuestion = (TextView) findViewById(R.id.question);
		tAnswer = (TextView) findViewById(R.id.answer);
		
		loadQuestion(index);
	}

	void loadQuestion(int i) {
		try {
			File f = new File(PATH + "question" + i + ".xml");
			dbFactory = DocumentBuilderFactory.newInstance();
			dBuilder = dbFactory.newDocumentBuilder();
			doc = dBuilder.parse(f);
			
			tQuestion.setText("Q"+i+": "+doc.getElementsByTagName("Name").item(0).getTextContent() + " - " + doc.getElementsByTagName("QuestionText").item(0).getTextContent());
			answer = doc.getElementsByTagName("AnswerText").item(0).getTextContent();
			tAnswer.setText("Press Button above to see the answer.");
		} catch (Exception e) {
			tAnswer.setText("Could not load Answer!");
			tQuestion.setText("Could not load Question!");
		}
		
	}

	void loadQuestion() {
		index = (int) Math.floor(Math.random() * max) + 1;
		loadQuestion(index);
	}
	
	void loadQuestionWithRanking(){
		int mult;
		int highest = 0;
		int highest_index = 0;
		
		for(int i = 0; i < max; i++){
			mult = (int) Math.floor(Math.random() * 10);
			if(highest < questionRating[i]*mult){
				highest = questionRating[i]*mult;
				highest_index = i + 1;
			}
			
		}

		index = highest_index;
		loadQuestion(index);
	}

	public void showAnswer(View view) {
		tAnswer.setText(answer);
	}

	public void next(View view) {
		if (index < max)
			index++;
		loadQuestion(index);
	}

	public void prev(View view) {
		if (index > 1)
			index--;
		loadQuestion(index);
	}

	public void random(View view) {
		loadQuestion();
		//loadQuestionWithRanking();
	}
	
	public void questionWasKnown(View view){
		questionRating[index -1] -= 1;
	}
	
	public void questionWasUnknown(View view){
		questionRating[index -1] += 1;
	
	}
	
	private void setQuestionRating(int startValue){
		for(int i = 0; i < max; i++){
			questionRating[i] = startValue;
		}
	}
	
}